package com.franklin.java.api.mybatis.dom.franklin;

import com.franklin.plugins.common.collection.PrettyArrayList;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import org.apache.commons.lang3.ArrayUtils;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 自定义Mapper对象，不适用idea的api
 * @author Franklin
 * @since 2021/8/24 16:43
 */
public class MyMapper {

    private XmlTag rootTag;

    private Map<String,XmlTag> idSqlTagMap = new HashMap<>();

    private List<MySelect> selectTags = new PrettyArrayList<>();

    public MyMapper(@NotNull XmlTag xmlTag) {
        this.rootTag = xmlTag;
        init();
    }

    private void init(){
        XmlTag[] subTags = rootTag.getSubTags();
        if (!ArrayUtils.isEmpty(subTags)) {
            for (XmlTag subTag : subTags) {
                if (subTag.getName().equals("sql")){
                    XmlAttribute idAttr = subTag.getAttribute("id");
                    String id = Optional.ofNullable(idAttr)
                        .map(XmlAttribute::getValue)
                        .orElse("");
                    idSqlTagMap.put(id,subTag);
                }else if (subTag.getName().equals("select")){
                    selectTags.add(new MySelect(subTag));
                }
            }
        }
    }

    public XmlTag getSql(String id){
        return idSqlTagMap.get(id);
    }

    public XmlTag getRootTag() {
        return rootTag;
    }


    public List<MySelect> getSelects() {
        return selectTags;
    }
}
